package com.bible.fire.local;

import java.lang.ref.WeakReference;

import com.bible.fire.pad.activity.BaseActivity;
import com.bible.fire.util.AndroidUtil;

import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;


public class PreposeHandler extends Handler {
	
	private static String TAG = PreposeHandler.class.getSimpleName();
	
	private WeakReference<Activity> mActivity = null;
	private WeakReference<Fragment> mFragment = null;
	
	public PreposeHandler(){		
	}

	public PreposeHandler( Activity activity ){
		if( activity != null ){
			mActivity = new WeakReference<Activity>( activity );
		}
	}
	
	public PreposeHandler(Fragment fragment){
		if( fragment != null ){
			mFragment = new WeakReference<Fragment>( fragment );
		}
	}
	
	public PreposeHandler( Activity activity, Fragment fragment){
		if( activity != null ){
			mActivity = new WeakReference<Activity>( activity );
		}
		if( fragment != null ){
			mFragment = new WeakReference<Fragment>( fragment );
		}
	}
	
	@Override
	public void handleMessage(Message m){
		Object result = null;
		if( mActivity != null && mActivity.get() == null ){
			return;
		}
		if( mFragment != null && (mFragment.get() == null || mFragment.get().getActivity() == null) ){
			return;
		}
		
		if( m.what == 1 ){					
		   Log.d(TAG, "handle response msg");
		   result = handleResponse( m.getData() );
		   afterHandle( result );			
		}else if( m.what == 0 ){
			hideProgressView();
			String tip = "操作失败,请检查网络状态";
			if( AndroidUtil.isNetworkAvailable() ){
				tip = "系统忙,请稍后重试";
			}
			Toast.makeText( AppContext.getContext(), tip, Toast.LENGTH_LONG).show();
		}		
	}
	
	//子类需覆盖此方法
	public Object handleResponse( Bundle data ){
		return null;
	}
	
	//处理完逻辑之后的后续操作(用户可覆盖此方法)，result为消息处理后的返回值
	public void afterHandle( Object result ){
		if( isAdjustViewAfterHandle() ){
		   hideProgressView();
		}	
	}
	
	//处理完毕之后是否隐藏等待界面
	public boolean isAdjustViewAfterHandle() {
		return true;
	}
	
	//处理完毕之后隐藏等待界面
	private void hideProgressView(){		
		Activity activity = null;
		if( mActivity != null && mActivity.get() != null ){
			activity = mActivity.get();			
		}else if( mFragment != null && mFragment.get() != null ){
			activity = mFragment.get().getActivity();			
		}
		if( activity != null && (activity instanceof BaseActivity) ){
			BaseActivity ta = (BaseActivity)activity;
			ta.dismissProgressDialog();
		}			
	}

}
